package com.bringspring.oauth.method.password.provider;

import com.bringspring.common.util.Md5Util;
import com.bringspring.oauth.method.detail.UserDetailsServiceImpl;
import com.bringspring.oauth.method.detail.UserExtend;
import com.bringspring.oauth.method.password.token.AccountPasswordAuthenticationToken;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 镜像密码校验
 */
@Component
public class AccountPasswordAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @SneakyThrows
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AccountPasswordAuthenticationToken accountAuthentication=(AccountPasswordAuthenticationToken)authentication;

        String username = accountAuthentication.getName();
        String passwordIn = accountAuthentication.getCredentials().toString();
        UserExtend userDetails = userDetailsService.loadUserByUsername(username);
        if (this.matches(passwordIn,userDetails.getSecretkey(), userDetails.getPassword())) {
            //如果密码匹配，则返回Authentication接口的实现以及必要的详细信息
            return authentication;
        } else {	//密码不匹配，抛出异常
            throw new BadCredentialsException("密码错误，请重试！");
        }
    }

    /**
     *  验证密码是否正确
     * @param rawEncoder 传入的密码
     * @param secretkey 密钥
     * @param encoder 数据库密码
     * @return
     */
    public boolean matches(CharSequence rawEncoder,String secretkey, String encoder) {
        return encoder.equals(Md5Util.getStringMd5(rawEncoder +secretkey.toLowerCase()));
    }
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(AccountPasswordAuthenticationToken.class);
    }
}
